package com.example.ams.service;

import com.example.ams.dto.ShiftSettingDTO;
import com.example.ams.entity.ShiftSetting;
import com.example.ams.repository.ShiftSettingRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 班次设置服务类
 * Shift Setting Service
 */
@Service
public class ShiftSettingService {

    @Autowired
    private ShiftSettingRepository shiftSettingRepository;

    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");

    /**
     * 获取当前生效的班次设置
     */
    public ShiftSettingDTO getCurrentShift() {
        ShiftSetting shift = shiftSettingRepository.findFirstByOrderByEffectiveDateDesc()
                .orElseThrow(() -> new RuntimeException("未找到班次设置"));
        return convertToDTO(shift);
    }

    /**
     * 创建或更新班次设置
     */
    @Transactional
    public ShiftSettingDTO saveOrUpdate(ShiftSettingDTO shiftDTO) {
        try {
            ShiftSetting shift = new ShiftSetting();
            
            if (shiftDTO.getId() != null) {
                shift = shiftSettingRepository.findById(shiftDTO.getId())
                        .orElse(new ShiftSetting());
            }

            shift.setWorkStart(Time.valueOf(shiftDTO.getWorkStart()));
            shift.setWorkEnd(Time.valueOf(shiftDTO.getWorkEnd()));
            shift.setLateGraceMin(shiftDTO.getLateGraceMin());
            shift.setEarlyGraceMin(shiftDTO.getEarlyGraceMin());
            shift.setEffectiveDate(shiftDTO.getEffectiveDate());

            ShiftSetting saved = shiftSettingRepository.save(shift);
            return convertToDTO(saved);
        } catch (Exception e) {
            throw new RuntimeException("保存班次设置失败: " + e.getMessage());
        }
    }

    /**
     * Entity转DTO
     */
    private ShiftSettingDTO convertToDTO(ShiftSetting shift) {
        ShiftSettingDTO dto = new ShiftSettingDTO();
        dto.setId(shift.getId());
        dto.setWorkStart(shift.getWorkStart().toString());
        dto.setWorkEnd(shift.getWorkEnd().toString());
        dto.setLateGraceMin(shift.getLateGraceMin());
        dto.setEarlyGraceMin(shift.getEarlyGraceMin());
        dto.setEffectiveDate(shift.getEffectiveDate());
        dto.setCreatedAt(shift.getCreatedAt());
        return dto;
    }
}

